package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    //菜品列表分页查询
    @GetMapping("/dish/page")
    public ResultInfo findByPage(@RequestParam(value = "page", defaultValue = "1") Integer pageNum,
                                 @RequestParam(defaultValue = "10") Integer pageSize, String name) {
        Page<Dish> page = dishService.findByPage(pageNum, pageSize, name);
        return ResultInfo.success(page);
    }

    //新增菜品
    @PostMapping("dish")
    public ResultInfo save(@RequestBody Dish dish) {
        //当我们新增一个菜品的时候,会影响到当前菜品分类列表的数据,
        // 需要从redis中根据key删除当前分类缓存
        String key = "dish_" + dish.getCategoryId();
        redisTemplate.delete(key);

        dishService.save(dish);
        return ResultInfo.success(null);
    }

    //根据主键查询菜品信息(菜品回显)
    @GetMapping("/dish/{id}")
    public ResultInfo findById(@PathVariable("id") Long id) {
        Dish dish = dishService.findById(id);
        return ResultInfo.success(dish);
    }

    //修改菜品
    @PutMapping("/dish")
    public ResultInfo update(@RequestBody Dish dish) {
        //删除当前Redis中所有的菜品分类
        Set keys = redisTemplate.keys("dish_*");//相当于keys dish_*
        redisTemplate.delete(keys);

        dishService.update(dish);
        return ResultInfo.success(null);
    }

    //删除
    @DeleteMapping("/dish")
    public ResultInfo deleteByIds(long[] ids) {
        //删除当前Redis中所有的菜品分类
        Set keys = redisTemplate.keys("dish_*");//keys dish_*
        redisTemplate.delete(keys);

        if (ids != null && ids.length > 0) {
            dishService.deleteByIds(ids);
        }
        return ResultInfo.success(null);
    }

    //启用 禁用
    @PostMapping("/dish/status/{status}")
    public ResultInfo updateByIds(@PathVariable("status") Integer status, Long[] ids) {
        //删除当前Redis中所有的菜品分类
        Set keys = redisTemplate.keys("dish_*");//keys dish_*
        redisTemplate.delete(keys);

        if (ids != null && ids.length > 0) {
            dishService.updateByIds(ids, status);
        }
        return ResultInfo.success(null);
    }

    //根据菜品分类id查询菜品列表  //根据菜品名称name查询菜品列表
    @GetMapping("/dish/list")
    public ResultInfo findByCategoryId(Long categoryId,String name) {
        List<Dish> dishList = dishService.findByCategoryId(categoryId);
        dishList = dishService.findByName(name);
        return ResultInfo.success(dishList);
    }




}
